package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IFollowService followService;

    @Override
    public Result queryHostBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog->{
            this.queryBlogUser(blog);
            this.isLikedBlog(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryById(Long id) {
        //查blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("fail not blog");
        }
        //查blog用户
        queryBlogUser(blog);
        isLikedBlog(blog);
        return Result.ok(blog);
    }

    private void isLikedBlog(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            //用户未登录，无需获取
            return;
        }
        Long userId = user.getId();
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result likeBlog(Long id) {
        //获取登录用户，是否点赞
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Double isMember = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (isMember == null) {
            //没点过
            boolean flag = update().setSql("liked = liked + 1").eq("id", id).gt("liked", 0).update();
            if (flag) {
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }
        else {
            boolean flag = update().setSql("liked = liked - 1").eq("id", id).gt("liked", 0).update();
            if (flag) {
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }

        }

    return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //zset查top5的点赞
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);
        //提取出来id
        List<Long> ids = null;
        if (top5 != null && !top5.isEmpty()) {
            ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        }else{
            return Result.ok(Collections.emptyList());
        }
        //查到用户
        //转成dto
        String strIds = StrUtil.join(",", ids);
        List<UserDTO> userDTO = userService
                .query().in("id",ids).last("ORDER BY FIELD(id," + strIds + ")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTO);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.ok("save blog failed!");
        }
        //拿到粉丝
        List<Follow> followUser = followService.query().eq("follow_user_id", blog.getUserId()).list();
        //循环读
         for (Follow follow:followUser) {
            //拿粉丝id
             Long userId = follow.getUserId();
             // 推送
             String key = "feed:" + userId;
             stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogFollow(Long max, Integer offset) {
        //查用户
        Long userId = UserHolder.getUser().getId();
        //查收信箱   ZREVRANGEBYSCORE key Max Min LIMIT offset count   args:(rawKey, min, max, offset, count);)
        String key = RedisConstants.FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //查数据blogId，offset，时间戳
        List<Long> ids =new ArrayList<>(typedTuples.size());
        int os =1;
        long minTime = 0;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
             ids.add(Long.valueOf(typedTuple.getValue()));
             long time = typedTuple.getScore().longValue();
            if (time != minTime) {
                minTime = time;
                os=1;
            }else {
                os++;
            }
        }
        String idsStr = StrUtil.join(",", ids);
        //根据id查blog
        List<Blog> blogs = query().in("id", ids).last("order by field(id," + idsStr + ")").list();
        //涉及blog要查
        for(Blog blog:blogs){
            queryBlogUser(blog);
            isLikedBlog(blog);
        }
        //封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
